package com.thb.pay.manage.comm.shiro.reflect;

import com.google.common.collect.Maps;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @Description ${description}
 * @Author lucky
 * @data 2019/8/30 0:32
 */
public class ReflectUtils {

    public static Object getInstance(Class<?> clazz, Map<String, Object> setKeyValueMap) throws Exception {
        Object obj = Class.forName(clazz.getName()).newInstance();
        Class<?> targetClazz = obj.getClass();
        Field[] fields = targetClazz.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                setKeyValueMap.keySet().forEach(key -> {
                    if (field.getName().equals(key) && field.getType() == setKeyValueMap.get(key).getClass()) {
                        try {
                            field.set(obj, setKeyValueMap.get(key));
                            return;
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
        return obj;
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> setKeyValueMap = Maps.newConcurrentMap();
        setKeyValueMap.put("age", 100);
        setKeyValueMap.put("name", "lucky");
        UserBean userBean = (UserBean) ReflectUtils.getInstance(UserBean.class, setKeyValueMap);
        System.out.println(userBean.toString());
    }
}
